<template>
  <div class="app-container">
    <el-card class="box-card">
      <div
        slot="header"
        class="clearfix"
      >
        <span>代理目账信息</span>
        <el-button
          v-if="restPas"
          style="float: right;"
          type="danger"
          icon="el-icon-setting"
          @click="setPassword"
        >重置密码
        </el-button>
      </div>
      <div>
        <el-row>
          <el-col :span="8">
            <div class="grid-content ">
              对账日期：{{ date }}
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content ">
              期初金额：{{ earlyMoney }}
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content ">
              期末金额：{{ endMoney }}
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card
      class="box-card"
      style="margin-top:20px"
    >
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane
          label="油站日账"
          name="first"
        >
          <div>
            <el-table
              :key="key"
              :data="walletDate"
              border
              fit
              highlight-current-row
              style="width: 100%;"
            >
              <el-table-column
                label="序号"
                prop="id"
                align="center"
                width="50"
              >
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column
                prop="cooperationName"
                label="油站名称"
                align="center"
                width=""
              />

              <el-table-column
                prop="date"
                label="对账日期"
                align="center"
                width=""
              />

              <el-table-column
                prop="created"
                label="对账时间"
                align="center"
                width="140"
              />

              <el-table-column
                prop="earlyMoney"
                label="期初金额"
                align="center"
                width="80"
              />

              <el-table-column
                prop="endMoney"
                label="期末金额"
                align="center"
                width="80"
              />

              <el-table-column
                prop="currentMoney"
                label="交易金额"
                align="center"
                min-width="80"
              />


              <el-table-column
                prop="preMoney"
                label="充值金额"
                align="center"
                min-width="80"
              />


              <el-table-column
                prop="cashMoney"
                label="退还金额"
                align="center"
                min-width="80"
              />

              <!--<el-table-column-->
                <!--label="操作"-->
                <!--align="center"-->
                <!--width=""-->
                <!--fixed="right"-->
              <!--&gt;-->
                <!--<template slot-scope="scope">-->
                  <!--<el-button-->
                    <!--v-if="scope.row.state==1"-->
                    <!--type="danger"-->
                    <!--size="mini"-->
                    <!--@click="delBankCard(scope.row)"-->
                  <!--&gt;解绑-->
                  <!--</el-button>-->

                  <!--<el-button-->
                    <!--v-if="scope.row.state==0"-->
                    <!--type="primary"-->
                    <!--size="mini"-->
                    <!--@click="handleGetMoney(scope.row)"-->
                  <!--&gt;绑定-->
                  <!--</el-button>-->
                  <!--<el-button-->
                    <!--type="info"-->
                    <!--size="mini"-->
                    <!--@click="getMasterCard(scope.row)"-->
                  <!--&gt;充值-->
                  <!--</el-button>-->
                <!--</template>-->
              <!--</el-table-column>-->
              -->
            </el-table>
          </div>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getWalletTradeList"
          />

        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      top="2vh"
      width="550px"
    >
      <el-form
        ref="temp"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item
          label="子卡名称"
          prop="name"
        >
          <el-input v-model="temp.name"/>
        </el-form-item>
        <el-form-item
          label="子卡卡号"
          prop="cardNum"
        >
          <el-input v-model="temp.cardNum"/>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="绑定加油站"
      :visible.sync="dialogFormMoney"
      top="2vh"
      width="600px"
    >
      <el-form
        ref="temp1"
        :rules="rules"
        :model="temp1"
        label-position="left"
        label-width="120px"
        style="width: 550px; margin-left:50px;"
        class="demo-dynamic"
        :inline="true"
      >
        <el-form-item
          label="子卡名称"
          prop=""
        >
          <el-input
            v-model="temp1.name"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item
          label="子卡卡号"
          prop=""
        >
          <el-input
            v-model="temp1.cardNum"
            :disabled="true"
          />
        </el-form-item>

        <el-form-item
          label="初始金额"
          prop=""
        >
          <el-input
            v-model="temp1.money"
          />
        </el-form-item>

        <el-form-item
          label="绑定加油站"
          prop="agentId"
        >
          <el-select
            v-model="temp1.cooId"
            class="filter-item"
          >
            <el-option
              v-for="item in tableDataCoo"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormMoney = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="getMoney()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>


    <el-dialog
      title="解绑加油站"
      :visible.sync="dialogFormunBind"
      top="2vh"
      width="600px"
    >
      <el-form
        ref="temp2"
        :rules="rules"
        :model="temp2"
        label-position="left"
        label-width="120px"
        style="width: 550px; margin-left:50px;"
        class="demo-dynamic"
        :inline="true"
      >
        <el-form-item
          label="子卡名称"
          prop=""
        >
          <el-input
            v-model="temp2.name"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item
          label="子卡卡号"
          prop=""
        >
          <el-input
            v-model="temp2.cardNum"
            :disabled="true"
          />
        </el-form-item>

        <el-form-item
          label="剩余金额"
          prop=""
        >
          <el-input
            v-model="temp2.money"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormunBind = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="unBindCard()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>


    <el-dialog
      title="子卡充值"
      :visible.sync="addSubMoneyDia"
      top="2vh"
      width="600px"
    >
      <el-form
        ref="temp3"
        :rules="rules"
        :model="temp3"
        label-position="left"
        label-width="120px"
        style="width: 550px; margin-left:50px;"
        class="demo-dynamic"
        :inline="true"
      >
        <el-form-item
          label="子卡名称"
          prop=""
        >
          <el-input
            v-model="temp3.name"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item
          label="子卡卡号"
          prop=""
        >
          <el-input
            v-model="temp3.cardNum"
            :disabled="true"
          />
        </el-form-item>

        <el-form-item
          label="主卡当前金额"
          prop=""
        >
          <el-input
            :disabled="true"
            v-model="temp3.currentMoney"
          />
        </el-form-item>
        <el-form-item
          label="充值金额"
          prop=""
        >
          <el-input
            v-model="temp3.money"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addSubMoneyDia = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="addSubMoney()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import {
    addBankCard,
    bankCardList,
    getPhoneCode,
    agentGetMoney,
    unBindBankCard,
    walletTradeList,
    getOilCardPage,
    addOrUpdateOilCard,
    cooperationAll,
    bindOilCard,
    unBindOilCard,
    subCardRech,
    getOilCardById,
    getCooVerifyPage
  } from '@/api/v1'
  import {resetPassword} from '@/api/user'
  import waves from '@/directive/waves' // Waves directive
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import {parseTime} from '@/utils'
  import {MessageBox, Message} from 'element-ui'

  export default {
    directives: {waves},
    components: {Pagination},
    filters: {
      walletTradeFilter(status) {
        switch (status) {
          case 0:
            return '已绑定'
          case 1:
            return '未绑定'
        }
      }
    },
    data() {
      return {
        restPas: false,
        tableData: [],
        walletDate: [],
        tableKey: 0,
        list: null,
        activeName: 'first',
        total: 0,
        listLoading: true,
        cooperation: [],
        tableDataCoo: [],
        listQuery: {
          page: 1,
          limit: 20,
          sort: '+id',
          date:'',
          agentId: ''
        },
        key: 1, // table key
        walletkey: 1, // table key
        dialogFormVisible: false,
        dialogFormMoney: false,
        dialogFormunBind: false,
        addSubMoneyDia: false,
        rules: {
          name: [{required: true, message: '请输入子卡名称', trigger: 'blur'}],
          cardNum: [{required: true, message: '请输入子卡卡号', trigger: 'blur'}],
        },
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        temp: {
          cardNum: '',
          name: '',
          state: 0,
          type: 2, // 省代或油卡商户id–超管添加必传
          parentId: '' // 类型1为省代，2为油卡商户–超管添加必传
        },
        temp1: {
          cardNum: null,
          name: null,
          cardId: null,
          cooId: null,
          money: null,
        },
        temp2: {
          cardNum: null,
          name: null,
          cardId: null,
          money: null,
        },
        temp3: {
          cardNum: null,
          name: null,
          cardId: null,
          currentMoney: null,
          money: null,
        }
      }
    },
    watch: {
      checkboxVal(valArr) {
        this.formThead = this.formTheadOptions.filter(
          i => valArr.indexOf(i) >= 0
        )
        this.key = this.key + 1 // 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
        this.walletkey = this.walletkey + 1 // 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
      }
    },

    created() {
      const type = this.$route.query.type // 1是省代  2是商户   是商户重置密码按钮隐藏
      if (type == 1) {
        this.restPas = true
      } else {
        this.restPas = false
      }


      this.agentId = this.$route.query.agentId
      this.date = this.$route.query.date
      this.endMoney = this.$route.query.endMoney
      this.earlyMoney = this.$route.query.earlyMoney
      this.listQuery.agentId = this.agentId
      this.listQuery.date = this.date

      this.getWalletTradeList()
    },
    methods: {
      //根据主卡id，查询主卡金额
      getMasterCard(row){
        getOilCardById({'id':this.temp.parentId}).then(res => {
          this.temp3.currentMoney = res.data.currentMoney;
          this.temp3.money = null;
          this.temp3.cardId = row.id;
          this.temp3.name = row.name;
          this.temp3.cardNum = row.cardNum;
          this.addSubMoneyDia = true
          this.$nextTick(() => {
            this.$refs['temp3'].clearValidate()
          })
        })
      },

      //子卡充值确认
      addSubMoney(){
        this.$refs['temp3'].validate(valid => {
          if (valid) {
            subCardRech(this.temp3).then(res => {
              this.addSubMoneyDia = false
              Message({
                message: res.msg || 'success',
                type: 'success',
                duration: 2 * 1000
              })
              this.getWalletTradeList();
            })
          }
        })
      },
      getAllCoo(){
        cooperationAll({'agentId': this.agentId}).then(res => {
          this.tableDataCoo = res.data;
        })
      },
      delBankCard(row) {
        this.temp2.money = null;
        this.temp2.cardId = row.id;
        this.temp2.name = row.name;
        this.temp2.cardNum = row.cardNum;
        this.dialogFormunBind = true
        this.$nextTick(() => {
          this.$refs['temp2'].clearValidate()
        })
      },
      setPassword() {
        const id = this.$route.query.relationId
        const data = {
          agentId: id
        }
        this.$confirm('此操作将重置该用户登录密码, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            resetPassword(data).then(res => {
              Message({
                message: res.msg || 'success',
                type: 'success',
                duration: 2 * 1000
              })
            })
          })
          .catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消删除'
            // });
          })
      },
      resetTemp() {
        this.temp.cardNum = ''
        this.temp.name = ''
      },
      handleCreate() {
        this.resetTemp()
        console.log(this.temp)
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['temp'].clearValidate()
        })
      },
      getCode() {
        var query = {phone: this.phone}
        getPhoneCode(query).then(res => {
          Message({
            message: res.msg || 'success',
            type: 'success',
            duration: 2 * 1000
          })
        })
      },
      getMoney() {
        this.$refs['temp1'].validate(valid => {
          if (valid) {
            bindOilCard(this.temp1).then(res => {
              this.dialogFormMoney = false
              Message({
                message: res.msg || 'success',
                type: 'success',
                duration: 2 * 1000
              })
              this.getWalletTradeList();
            })
          }
        })
      },
      unBindCard() {
        this.$refs['temp2'].validate(valid => {
          if (valid) {
            unBindOilCard(this.temp2).then(res => {
              this.dialogFormunBind = false
              Message({
                message: res.msg || 'success',
                type: 'success',
                duration: 2 * 1000
              })
              this.getWalletTradeList();
            })
          }
        })
      },
      handleGetMoney(row) {

        this.temp1.money = null;
        this.temp1.cooId = null;
        this.temp1.cardId = row.id;
        this.temp1.name = row.name;
        this.temp1.cardNum = row.cardNum;
        this.dialogFormMoney = true
        this.$nextTick(() => {
          this.$refs['temp1'].clearValidate()
        })
      },

      handleDownload() {
        down(this.listQuery).then(res => {
          console.log(res)
          this.$router.push({
            path: '/down'
          })
        })
      },
      getList() {
        this.listLoading = true
        getOilCardPage(this.listQuery).then(res => {
          this.tableData = res.data.records

          console.log(this.tableData)
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      getWalletTradeList() {
        getCooVerifyPage(this.listQuery).then(res => {
          this.walletDate = res.data.records
          console.log(this.walletDate)
          this.total = Number(res.data.total)
        })
      },
      createData() {
        this.$refs['temp'].validate(valid => {
          if (valid) {
            addOrUpdateOilCard(this.temp).then(res => {
              // this.list.unshift(this.temp);
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: res.msg,
                type: 'success',
                duration: 2000
              })
              this.getWalletTradeList();
            })
          }
        })
      },
      handleClick(tab, event) {
        console.log(tab, event)
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      }
    },
    filters: {
      walletTradeFilter(status) {
        switch (status) {
          case 1:
            return '+'
          case 2:
            return '-'
        }
      }
    },
  }
</script>

